package com.xyebank.cn.project.controller;


import com.xyebank.cn.project.entity.CreateInfo;
import com.xyebank.cn.project.util.CreateCodeUtil;
import com.xyebank.cn.project.util.ZipUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

@RestController
public class IndexController {

    @Autowired
    private ZipUtil zipUtil;

    private final Logger logger=LoggerFactory.getLogger(this.getClass());
    /**
     * 文件上传路径
     */
    @Value("${upload.path}")
    private String uploadPath;

    /**
     * 项目运行环境
     */
    @Value("${spring.profiles.active}")
    private String active;

    public static  final  String APPLICATION_FTL="application";

    public static  final  String POM_FTL="pom";

    public static  final String PROPERTIES_FTL="properties";

    public static  final String TEST_FTL="test";


    @Autowired
    private Configuration configuration;

    /**
     * 项目生成主页面
     * @return
     */
    @RequestMapping("/")
    public ModelAndView index(){
        ModelAndView mv=new ModelAndView("/view/index");
        return mv;
    }

    /**
     * 创建项目
     * @return
     */
    @RequestMapping("/createProject")
    public String createProject(CreateInfo createInfo, HttpServletResponse response){
        //创建项目的路径将项目创建在 templete下的rar 文件中
        File path = null;
        byte[] buffer = new byte[1024];
        FileInputStream fis = null; //文件输入流
        BufferedInputStream bis = null;
        OutputStream os = null; //输出流
        File downFile=null;

        logger.info("开始创建项目，项目路径为："+uploadPath);
        response.setContentType("application/force-download");
        response.setHeader("Content-Disposition", "attachment;fileName=" + createInfo.getArtifact()+".zip");

        try {
            createZip(createInfo,uploadPath);
            String zipName=uploadPath+createInfo.getArtifact()+".zip";
            downFile=  new File(zipName);
            os = response.getOutputStream();
            fis = new FileInputStream(downFile);
            bis = new BufferedInputStream(fis);
            int i = bis.read(buffer);
            while(i != -1){
                os.write(buffer);
                i = bis.read(buffer);
                os.flush();
            }

            logger.info("----------file download" + createInfo.getArtifact()+".zip");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
                fis.close();
                downFile.delete();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return "";
    }

    /**
     * 创建压缩文件
     * @param createInfo  上传的信息
     * @param uploadPath  上传项目的路径
     */
    private void createZip(CreateInfo createInfo, String uploadPath) {

        logger.info("当前项目环境为："+active);

        //设置项目上传路径
        String  projPath=uploadPath+createInfo.getArtifact()+"/";
        CreateCodeUtil.checkParentFilePath(projPath);
        logger.info("项目生成路径为："+projPath);
        try {
            /**
             * 生成application 文件
             */
            CreateCodeUtil.createApplication(configuration.getTemplate(APPLICATION_FTL+".ftl"),createInfo,projPath);

            /**
             * 生成pom.xml文件
             */
            CreateCodeUtil.createPom(configuration.getTemplate(POM_FTL+".ftl"),createInfo,projPath);

            /**
             * 生成properties文件
             */
            CreateCodeUtil.createProperties(configuration.getTemplate(PROPERTIES_FTL+".ftl"),createInfo,projPath);

            /**
             * 生成test
             */
            CreateCodeUtil.createTest(configuration.getTemplate(TEST_FTL+".ftl"),createInfo,projPath);

            /**
             * 压缩项目 将项目压缩成zip文件
             */
            zipUtil.dozip(projPath,uploadPath+createInfo.getArtifact()+".zip");

            /**
             * 最后删除掉生成的文件
             */
            File proFile=new  File(projPath);
            FileUtils.deleteDirectory(proFile);

        } catch (IOException e) {
            e.printStackTrace();
        }


    }


}
